import {app, BrowserWindow} from 'electron'
import pie from 'puppeteer-in-electron'
import puppeteer from 'puppeteer-core';
import handleBaiduPcSearch from './baiduPcSearch'
import handleBaiduMobileSearch from './baiduMobileSearch'
import handleDouyinLiveListener from './douyinLive'

//初始化 puppeteer
var browser; //浏览器
(async () => {
    await pie.initialize(app);
    browser = await pie.connect(app, puppeteer);
})();

var win;
var closeBrowserWindow = () => {
    win && win.close()  //防止存在窗口未关闭
}
//创建 puppeteer 窗口
var createPuppeteerWindow = async (config) => {
    closeBrowserWindow()  //防止存在窗口未关闭
    config = config || {}   //防止参数未传递
    win = new BrowserWindow({
        width: config.width || 1920,
        height: config.height || 1080,
        show: config.show != null ? config.show : true,
        webPreferences: {
            devTools: true
        }
    });
    win.webContents.setAudioMuted(true) //静音
    win.on('close', () => {
        console.log("关闭了浏览器窗口")
        win = null
    })
    var page = await pie.getPage(browser, win);
    return {win, page}
}

//pc百度排名搜索
var baiduPcSearch = async (keywords) => {
    //创建窗口
    var {win, page} = await createPuppeteerWindow({width: 1280, height: 960})
    //处理搜索
    var resultArray = await handleBaiduPcSearch(page, keywords)
    //关闭窗口（防止下次使用异常）
    if (keywords && keywords.length) {
        win.close(); //自动搜索，自动关闭窗口
    }
    return resultArray;
}

//手机百度排名搜索
var baiduMobileSearch = async (keywords) => {
    //创建窗口
    var {win, page} = await createPuppeteerWindow({width: 400, height: 812})
    //处理搜索
    var resultArray = await handleBaiduMobileSearch(page, keywords)
    //关闭窗口（防止下次使用异常）
    if (keywords && keywords.length) {
        win.close(); //自动搜索，自动关闭窗口
    }
    return resultArray;
}


//抖音直播监听器（弹幕）
var douyinLiveListener = async (link, event) => {
    //创建窗口
    var {win, page} = await createPuppeteerWindow({width: 700, height: 812, show: false})
    //处理搜索
    await handleDouyinLiveListener(page, link, event)
    return win;
}

export {
    closeBrowserWindow,
    baiduPcSearch,
    baiduMobileSearch,
    douyinLiveListener
}
